using System;
using System.Text;
using System.Data;

namespace Antu.Core.Ajax
{
    /// <summary>
    /// Provides methods to serialize and deserialize a Guid object.
    /// </summary>
    public class GuidConverter : AbstractJavascriptConverter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="GuidConverter"/> class.
        /// </summary>
        public GuidConverter()
            : base()
        {
            serializabletypeslist = new Type[] {
				typeof(Guid)
			};
            deserializabletypeslist = serializabletypeslist;
        }

        /// <summary>
        /// Converts a .NET object into a JSON string.
        /// </summary>
        /// <param name="o">The object to convert.</param>
        /// <returns>Returns a JSON string.</returns>
        public override string Serialize( object o )
        {
            StringBuilder sb = new StringBuilder();
            Serialize( o , sb );
            return sb.ToString();
        }

        /// <summary>
        /// Serializes the specified o.
        /// </summary>
        /// <param name="o">The o.</param>
        /// <param name="sb">The sb.</param>
        public override void Serialize( object o , StringBuilder sb )
        {
            // Guids are not supported by JavaScript, we will return the
            // string representation using following format:
            // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 

            JavaScriptUtil.QuoteString( o.ToString() , sb );
        }

        /// <summary>
        /// Converts an IJSONObject into an NET object.
        /// </summary>
        /// <param name="o">The IJSONObject object to convert.</param>
        /// <param name="t"></param>
        /// <returns>Returns a .NET object.</returns>
        public override object Deserialize( IJavascriptObject o , Type t )
        {
            return new Guid( o.ToString() );
        }
    }
}
